from django.shortcuts import render, redirect, HttpResponse
from tools.md5prc import encrypt
from Hosts.models import CallCircuit,Host,UserInfo
from tools.paginator import Pagination
import json, random

# Create your views here.

def auth(func):
    def inner(request,*args,**kwargs):
        ck = request.session.get('UserName')
        if not ck:
            return redirect('Login')
        return func(request,*args,**kwargs)
    return inner

def login(request):
    '''
    登陆请求
    :param request: 
    :return: login网页
    '''
    res = {"status":False}
    if request.method == 'GET':
        return render(request, 'hosts/login.html')
    else:
        # print(request.POST)
        user = request.POST.getlist('username')[0]
        pwd = request.POST.getlist('pwd')[0]
        pwd = encrypt(pwd)
        # print(pwd)
        obj = UserInfo.objects.filter(UserName=user, PassWd=pwd).first()
        if obj:
            request.session['UserName'] = user
            res["status"] = True
        else:
            res["msg"] = "用户名或密码错误"
        return HttpResponse(json.dumps(res))

@auth
def index(request):
    '''
    首页
    :return: 
    '''
    res = {}
    if request.method == 'GET':
        #all_user_list = UserInfo.objects.all()
        all_line_list = CallCircuit.objects.all()

        # 分页功能
        all_host_count = Host.objects.all().count()
        current_page = request.GET.get('page')
        page_obj = Pagination(current_page, all_host_count,'/hosts/index/')

        host_list = Host.objects.all()[page_obj.start:page_obj.end]
        page_str = page_obj.page_html()
        res = {"host_list": host_list, 
               #"all_user_list":all_user_list,
               "all_line_list":all_line_list,
               "page_str":page_str}
    return render(request, 'hosts/index.html', res)

@auth
def logout(request):
    '''
    注销登录
    :param request: 
    :return: 
    '''
    request.session.clear()
    # print('Logout', request.session.get('UserName'))
    return redirect('Login')

@auth
def delHosts(request):
    '''
    删除
    :param request: 
    :return: 
    '''
    res = {"status":False}
    if request.method == "POST":
        id=request.POST.get("sid")
        Host.objects.filter(id=id).delete()
        res["status"] = True
    return HttpResponse(json.dumps(res))

@auth
def showHost(request):
    '''
    查看主机
    :param request: 
    :return: 
    '''
    res = {"status": False}
    if request.method == 'POST':
        row_id = request.POST.get('sid')
        row_obj = Host.objects.filter(id=row_id)
        row_list = row_obj.values("id", "Name", "IP",
                                  "Port", "User", "SshKey", "PassWd",
                                  "callCircuit__Name")[0]
        res["status"] = True
        res.update(row_list)
    return HttpResponse(json.dumps(res))

@auth
def editHost(request):
    '''
    编辑Host表
    :param request: 
    :return: 返回true false的json字典
    '''
    res = {"status": False, "message":"更新失败，请检查输入"}
    if request.method == 'POST':
        id = request.POST.get('id')
        name = request.POST.get('SE-name')
        ip = request.POST.get('SE-ip')
        port = request.POST.get('SE-port')
        callCircuit_num = request.POST.get('callCircuit')
        user = request.POST.get('SE-user')
        pwd = request.POST.get('SE-passwd')
        sshKey = request.POST.get('SE-sshKey')

        Host.objects.filter(id=id).update(Name=name, IP=ip,
                                  Port=port, User=user, SshKey=sshKey,
                                  PassWd=pwd,callCircuit_id=callCircuit_num)
        res["status"] = True
    return HttpResponse(json.dumps(res))


@auth
def callUser(request, **call_id):
    '''
    显示特定业务的用户列表
    :param request: 
    :return: 用户列表
    '''
    if request.method == "GET":
        user_list = UserInfo.objects.filter(callCircuit=call_id['call_id'])
    return render(request, 'hosts/calluser.html', {'user_list':user_list})


def addHosts(request):
    '''
    批量生产Hosts测试数据
    :param request: 
    :return: 
    '''
    Port = 23456
    User = "root"
    for i in range(1,22):
        Name = "host%s.name.com" % i
        IP = "192.168.1.%s" % i
        callCircuit = random.randint(1,4)
        Host.objects.create(Name=Name, Port=Port, User=User,IP=IP, callCircuit_id=callCircuit)
    return HttpResponse('创建成功')